package com.tarena.lbs.user.service.impl;

import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.dao.repository.UserRepository;
import com.tarena.lbs.user.dao.repository.UserTagsRepository;
import com.tarena.lbs.user.pojo.param.UserParam;
import com.tarena.lbs.user.pojo.param.UserTagsParam;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.pojo.po.UserTagsPO;
import com.tarena.lbs.user.pojo.vo.UserVO;
import com.tarena.lbs.user.service.UserService;
import com.tarena.lbs.user.utils.RandomUserName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserTagsRepository userTagsRepository;

    @Autowired
    private UserRepository userRepository;


    @Override
    public void register(UserParam param) throws BusinessException {
        String phone = param.getPhone();
        Long count = userRepository.countUserByPhone(phone);
        Asserts.isTrue(count>0,new BusinessException("-2","手机号已经存在"));
        //2.封装数据
        UserPO poParam = assembleUserPO(param);
        //3.直接写入数据库
        userRepository.save(poParam);
    }

    @Override
    public UserVO detail() throws BusinessException {
        //1.解析jwt 拿到userPrinciple
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        Integer userId = userPrinciple.getId();
        //2.仓储层查询唯一的po
        UserPO po = userRepository.getById(userId);
        Asserts.isTrue(po==null,new BusinessException("-2","用户信息不存在"));
        //3.转化vo
        UserVO vo=new UserVO();
        BeanUtils.copyProperties(po,vo);
        return vo;
    }

    @Override
    public void bindUserTags(UserTagsParam param) throws BusinessException {
        // 1.解析jwt获取用户ID
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null, new BusinessException("-2", "用户认证解析失败"));
        Integer userId = userPrinciple.getId();

        log.info("开始绑定用户标签，用户ID: {}, 参数: {}", userId, param);

        // 2.参数校验 - 只有当参数不为null时才进行空值校验
        if (param != null && param.getTagIds() != null && !param.getTagIds().isEmpty()) {
            // 3.删除用户原有标签关联
            userTagsRepository.deleteByUserId(userId);
            log.info("已删除用户{}的旧标签关联", userId);

            // 4.保存新的标签关联
            String[] tagIdArray = param.getTagIds().split(",");
            int savedCount = 0;
            for (String tagId : tagIdArray) {
                // 确保tagId不为空且是有效数字
                if (tagId != null && !tagId.trim().isEmpty()) {
                    try {
                        UserTagsPO userTagsPO = new UserTagsPO();
                        userTagsPO.setUserId(userId);
                        userTagsPO.setTagId(Integer.valueOf(tagId.trim()));
                        userTagsRepository.save(userTagsPO);
                        savedCount++;
                    } catch (NumberFormatException e) {
                        log.warn("无效的标签ID: {}", tagId);
                    }
                }
            }
            log.info("为用户{}保存了{}个标签关联", userId, savedCount);

            // 5.更新用户状态为已绑定标签
            UserPO userPO = userRepository.getById(userId);
            if (userPO != null) {
                userPO.setStatus(1); // 1表示已绑定标签
                userRepository.update(userPO);
                log.info("更新用户{}状态为已绑定标签", userId);
            }
        } else {
            log.warn("用户标签参数为空或标签ID为空，用户ID: {}", userId);
        }
    }

    private UserPO assembleUserPO(UserParam param) {
        UserPO po=new UserPO();
        BeanUtils.copyProperties(param,po);
        //补充必要数据 用户状态 0表示没有绑定标签 1 表示绑定了标签
        po.setStatus(0);
        //用户昵称 注册时候 不是用户填写的 为了快速注册 我们随机生成一个
        String randomName = RandomUserName.createRandomName();//老 大 小  张王李赵
        po.setNickName(randomName);
        po.setUserName(randomName);
        //注册时间
        po.setRegTime(new Date());
        return po;
    }

}
